package com.github.caijh.mall.interceptor;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.github.caijh.framework.web.util.RequestUtils;
import com.github.caijh.mall.common.CommonResult;
import com.github.caijh.mall.common.validator.AdminTokenValidator;
import com.github.caijh.mall.constants.Constants;
import org.springframework.web.servlet.HandlerInterceptor;


public class AdminTokenInterceptor implements HandlerInterceptor {

    private final AdminTokenValidator adminTokenValidator;

    public AdminTokenInterceptor(AdminTokenValidator adminTokenValidator) {
        this.adminTokenValidator = adminTokenValidator;
    }

    //程序处理之前需要处理的业务
    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, HttpServletResponse response, @Nonnull Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String token = RequestUtils.extractHeader(request, Constants.HEADER_AUTHORIZATION_KEY);

        if (token == null || token.isEmpty()) {
            response.getWriter().write(JSON.toJSONString(CommonResult.unauthorized()));
            return false;
        }

        boolean result = adminTokenValidator.validate(token);
        if (!result) {
            response.getWriter().write(JSON.toJSONString(CommonResult.unauthorized()));
            return false;
        }
        return true;
    }

}
